import { resolve, basename, extname, sep } from 'path'
import { readdirSync, statSync, writeFileSync, readFileSync } from 'fs'
import { fileURLToPath } from 'url'
import glob from 'glob'

export interface FilesList {
    path: string
    name: string
}

const FilePaths = (dir: string) => fileURLToPath(new URL(dir, import.meta.url))
// 获取文件集合
export function readFileList(path: string, filesList: FilesList[]) {
    readdirSync(path).forEach(function (item) {
        let stat = statSync(resolve(path, item))
        // stat.isDirectory() 判断是否文件夹 ||  stat.isFile() 判断是否文件
        if (stat.isFile()) {
            if (/\.(vue|jsx|tsx)/g.test(extname(item))) {
                filesList.push({
                    path: path, // 路径
                    name: basename(item, extname(item)), // 名字
                })
            }
        } else if(stat.isDirectory() && item !== 'components') {
            // 文件夹再次递归读取文件
            readFileList(resolve(path, item), filesList)
        }
    })
}

export function useAuthRoute() {
	let componentsList = ''
    let componentsCollection = '\nexport default {\n'
	glob.sync('src/views/**/*.{vue,jsx,tsx}')
		.filter(i => !/(components|App)/g.test(i))
		.forEach(i => {
			const name = basename(i, extname(i))
			const path = i.slice(i.indexOf('/src') + 4)
			componentsList += `export const ${name} = () => import('@${path}');\n`
			componentsCollection += `  ${name},\n`
		})
    componentsCollection += '}'
    try {
        writeFileSync(
            FilePaths('../views/index.ts'),
            componentsList + componentsCollection,
            'utf8'
        )
    } catch (e) {
        console.log('文件写入错误=>>>', e)
    }
}

// export function useAuthRoute() {
// 	let componentsList = ''
//     let componentsCollection = '\nexport default {\n'
// 	const filesList: FilesList[] = []
//     readFileList(FilePaths('../views'), filesList)
// 	filesList.forEach(i => {
// 		let path = `${i.path}${sep}${i.name}.vue`.split(sep).join('/')
//         path = path.slice(path.indexOf('/src') + 4)
// 		componentsList += `export const ${i.name} = () => import('@${path}');\n`
// 		componentsCollection += `  ${i.name},\n`
// 	})
//     componentsCollection += '}'
//     try {
//         writeFileSync(
//             FilePaths('../views/index.ts'),
//             componentsList + componentsCollection,
//             'utf8'
//         )
//     } catch (e) {
//         console.log('文件写入错误=>>>', e)
//     }
// }
